#include <iostream>
#include <map>
#include <string>
using namespace std;

// 饿汉模式:直接使用静态对象，会导致进程启动时间变长

class hungry
{
public:
    static hungry &getInstance()
    {
        return obj_;
    }
    void add(const int &key, const string &value)
    {
        m_[key] = value;
    }
    void print()
    {
        for (auto kv : m_)
        {
            cout << kv.first << ":" << kv.second << endl;
        }
    }

private:
    hungry()
    {
    }
    hungry(const hungry &aa) = delete;
    hungry &operator=(const hungry &aa) = delete;
    map<int, string> m_;
    static hungry obj_;
};

// int A::_scount = 0; 类型 类域::变量名 = XX ,有模板必须把模板带上;
hungry hungry::obj_;

// 懒汉模式:写成静态指针只有在调用getinstance的时候才会建立实例
class lazy
{
public:
    static lazy *getInstance()
    {
        if (obj_ == nullptr)
        {
            obj_ = new lazy();
        }
        return obj_;
    }
    void add(const string &key, const int &value)
    {
        m_[key] = value;
    }
    void print()
    {
        for (auto kv : m_)
        {
            cout << kv.first << ":" << kv.second << endl;
        }
    }
    static void delIntanse()
    {
        if (obj_ != nullptr)
        {
            delete obj_;
            obj_ = nullptr;
        }
    }

private:
    lazy()
    {
    }
    ~lazy()
    {
        //obj_对象析构走到了这里
        cout<<"析构"<<endl;
    }
    lazy(const lazy &aa) = delete;
    lazy &operator=(const lazy &aa) = delete;
    map<string, int> m_;
    static lazy *obj_;
    //整个gc是用于自动回收资源的
    class gc
    {
    public:
        ~gc()
        {
            delIntanse();
        }
    };
    static gc _gc;
};

lazy *lazy::obj_ = nullptr;
// 类型 类域::变量名 = XX
lazy::gc lazy::_gc;

int main()
{
    lazy::getInstance()->add("a", 1);
    lazy::getInstance()->add("b", 2);
    lazy::getInstance()->add("c", 3);
    lazy::getInstance()->print();
    lazy::delIntanse();
    hungry::getInstance().add(1, "a");
    hungry::getInstance().add(2, "b");
    hungry::getInstance().add(3, "c");
    hungry::getInstance().print();
}